package com.shycloud.mido.member.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.member.api.entity.Member;
import com.shycloud.mido.member.api.entity.OrgOrganization;
import com.shycloud.mido.member.api.entity.OrgStudentDetailed;
import com.shycloud.mido.member.api.entity.OrgTeacherDetailed;
import com.shycloud.mido.member.api.vo.MemberDetailForLoginVO;
import com.shycloud.mido.member.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component("APPLE")
@AllArgsConstructor
public class AppleLoginHandler extends AbstractLoginHandler {

	/** 会员模块 service */
	private final MemberServiceV2 memberService;
	/** 注册模块 service */
	private final RegisterService registerService;
	/** 教师模块 service */
	private final OrgTeacherDetailedService teacherDetailedService;
	/** 学生模块 service */
	private final OrgStudentDetailedService studentDetailedService;
	/** 机构模块 service */
	private final OrgOrganizationService orgOrganizationService;
	/** redis 模块 */
	private final RedisTemplate redisTemplate;

	/**
	 * IOS AppleID
	 * <p>
	 * 通过code 调用qq 获取唯一标识
	 *
	 * @param appleId
	 * @return
	 */
	@Override
	public String identify(String appleId) {
		return appleId;
	}

	/**
	 * openId 获取用户信息
	 *
	 * @param appleId
	 * @return
	 */
	@Override
	public MemberDetailForLoginVO info(String appleId) {

		String[] appleArr = appleId.split("TOKENJY");

		Member member = memberService
				.getOne(new QueryWrapper<Member>().eq("apple_openid", appleArr[0]));


		MemberDetailForLoginVO memberDetailForLoginVO = new MemberDetailForLoginVO();

		//IOS 没有绑定用户的场合
		if (member == null) {
			//新增用户
			registerService.iosRegister(appleArr[0], appleArr[1]);
			//重新查询
			member = memberService.getOne(new QueryWrapper<Member>().eq("apple_openid", appleArr[0]));
		} else {
			member.setAppleToken(appleArr[1]);
			memberService.updateById(member);
		}

		BeanUtils.copyProperties(member, memberDetailForLoginVO);

		//身份为教师
		if ("1".equals(memberDetailForLoginVO.getIsTeacher())) {
			//查询教师表，获取默认机构ID
			List<OrgTeacherDetailed> teacherDetaileds = teacherDetailedService
					.list(new QueryWrapper<OrgTeacherDetailed>()
							.eq(OrgTeacherDetailed.COL_MEMBER_ID, memberDetailForLoginVO.getId())
							.and(x -> x.eq(OrgTeacherDetailed.COL_DEL_FLAG, "0"))
							.orderByAsc(OrgTeacherDetailed.COL_CREATE_TIME));

			if (teacherDetaileds.size() == 0) {
				log.info("未查询到所在机构，用户名为:{}", memberDetailForLoginVO.getUsername());
				return null;
			} else {
				//获取机构信息
				OrgOrganization org = orgOrganizationService
						.getById(teacherDetaileds.get(0).getOrgId());
				//机构ID
				memberDetailForLoginVO.setOrgId(org.getId());
				//机构名
				memberDetailForLoginVO.setOrgName(org.getName());
			}

		}

		//身份为学生
		else {

			//查询教师表，获取默认机构ID
			List<OrgStudentDetailed> studentDetaileds = studentDetailedService
					.list(new QueryWrapper<OrgStudentDetailed>()
							.eq(OrgStudentDetailed.COL_MEMBER_ID, memberDetailForLoginVO.getId())
							.and(x -> x.eq(OrgStudentDetailed.COL_DEL_FLAG, "0"))
							.orderByAsc(OrgStudentDetailed.COL_CREATE_TIME));

			if (studentDetaileds.size() > 0) {
				if (studentDetaileds.get(0).getOrgId() != 0) {
					//获取机构信息
					OrgOrganization org = orgOrganizationService
							.getById(studentDetaileds.get(0).getOrgId());
					//机构ID
					memberDetailForLoginVO.setOrgId(org.getId());
					//机构名
					memberDetailForLoginVO.setOrgName(org.getName());
				} else {
					//机构ID
					memberDetailForLoginVO.setOrgId(0);
					//机构名
					memberDetailForLoginVO.setOrgName("暂无机构");
				}
			} else {

				//false 代表 redis 有这个键就不能继续操作了
				Boolean saveStudentRedis = redisTemplate.opsForValue()
						.setIfAbsent("saveStudent_" + member.getId(), "1", 5, TimeUnit.SECONDS);
				if (saveStudentRedis) {
					//新建学生身份，orgId为0，暂无机构
					//创建学生用户
					OrgStudentDetailed student = new OrgStudentDetailed();
					//memberId
					student.setMemberId(memberDetailForLoginVO.getId());
					//机构ID
					student.setOrgId(0);
					//创建时间
					student.setCreateTime(new Date());
					//逻辑删除
					student.setDelFlag(CommonConstants.STATUS_NORMAL);
					//昵称
					student.setName(memberDetailForLoginVO.getShowname());

					studentDetailedService.save(student);
				}
				//机构ID
				memberDetailForLoginVO.setOrgId(0);
				//机构名
				memberDetailForLoginVO.setOrgName("暂无机构");
			}
		}
		return memberDetailForLoginVO;
	}

}
